﻿using AutoMapper;
using MediatR;
using SmartProduction.Domain.采购委外订单;
using SmartProduction.ErrorCode;
using SmartProduction.Infarstructrue.Interface;
using SmartProduction.Read.API.Application.Commands.ProcessRouteCommand;

namespace SmartProduction.Read.API.Application.CommandHandlers.ProcessRouteCommandHandler
{
    /// <summary>
    /// 工艺路线命令处理
    /// </summary>
    public class ProcessRouteQueryCommandHandler : IRequestHandler<ProcessRouteQueryCommand, APIPaing<List<ProcessRoute>>>
    {
        /// <summary>
        /// AutoMapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 仓储-工艺路线
        /// </summary>
        private readonly IBaseRepository<ProcessRoute> processRepository;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="processRepository"></param>
        public ProcessRouteQueryCommandHandler(IMapper mapper, IBaseRepository<ProcessRoute> processRepository)
        {
            this.mapper = mapper;
            this.processRepository = processRepository;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">实体</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<APIPaing<List<ProcessRoute>>> Handle(ProcessRouteQueryCommand request, CancellationToken cancellationToken)
        {
            APIPaing<List<ProcessRoute>> result = new APIPaing<List<ProcessRoute>>();
            var list = processRepository.GetAll().Result.Where(o => o.IsDelete == 0);
            if (!string.IsNullOrEmpty(request.ProcessCod))
            {

                list = list.Where(o => o.ProcessCod == request.ProcessCod);
            }
            if (!string.IsNullOrEmpty(request.ProcessName))
            {
                list = list.Where(o => o.ProcessName.Contains(request.ProcessName));
            }
            if (!string.IsNullOrEmpty(request.Status))
            {

                list = list.Where(o => o.Status == request.Status);
            }
            if (!string.IsNullOrEmpty(request.Material))
            {

                list = list.Where(o => o.Material == request.Material);
            }
           
            result.TotalCount = list.Count();
            result.PageCount = (int)Math.Ceiling((double)result.TotalCount / request.PageSize);
            list = list.OrderByDescending(o => o.Processid).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            var data = mapper.Map<List<ProcessRoute>>(list);
            result.Code = APIEnums.查询成功;
            result.Msg = APIEnums.查询成功.ToString();
            result.data = data;
            return await Task.FromResult(result);
        }
    }
}
